package com.hjc.demo.quartz;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

public class HelloScheduler {
    public static void main(String[] args) throws SchedulerException, InterruptedException {
        //创建jobDetail绑定HelloJob
//        HelloJob1 job1 = new HelloJob1();
//        job1.setData(()->"joobbbbbb");
        HelloJob1.setData(() -> "sdfsdf");
        JobDetail jobDetail = JobBuilder.newJob(HelloJob1.class)
                .withIdentity("myJob","myGroup").build();
        //创建触发器trigger每个2秒执行一次，一直执行
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity("mtTrigger", "myGroup").startNow()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds(2).repeatForever()).build();
        //创建调度者工厂
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        //创建调度者
        Scheduler scheduler = schedulerFactory.getScheduler();

        //启动调度器
        scheduler.start();
        //设置调度任务
        scheduler.scheduleJob(jobDetail, trigger);
        TimeUnit.SECONDS.sleep(6);
        scheduler.pauseJob(jobDetail.getKey());
        System.out.println("asdfdd");
        scheduler.start();
        System.out.println("ddd");
        TimeUnit.SECONDS.sleep(6);
        System.out.println("重启");
        scheduler.resumeJob(jobDetail.getKey());
    }

 // 内部类不能使用，静态内部类可以
    public static class HelloJob1 implements Job {

     {
         System.out.println("first");
     }

     public HelloJob1() {
         System.out.println("asfd");
     }

     {
         System.out.println("finish");
     }

        private static Supplier<String> supplier;

        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        @Override
        public void execute(JobExecutionContext context) throws JobExecutionException {
            Date now = new Date();
            String currentTime = sdf.format(now);
            System.out.println(supplier == null);
            System.out.println("执行时间为：" +supplier.get()+ currentTime);
        }


        public static void  setData(Supplier<String> suppliertemp) {
            supplier = suppliertemp;
        }
    }
}
